package org.example.controller;

import org.example.dao.StudentMapper;
import org.example.pojo.Student;
import org.example.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings("ALL")
@Controller
public class ToolController {

    @Autowired
    private StudentMapper studentMapper;

    @GetMapping("/upload")
    public String upload() {
        return "uploadExcel";
    }

    @RequestMapping("/uploadExcel")
    @ResponseBody
    public String uploadExcel(HttpServletRequest request){
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartHttpServletRequest.getFile("excelFile");

        String filename = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            List <List<Object>> lists = ExcelUtil.getCourseListByExcel(inputStream, filename);

            //完成解析
            if (lists.size() > 0) {
                Iterator<List <Object>> iterator = lists.iterator();
                ArrayList <Student> students = new ArrayList<>();
                while (iterator.hasNext()) {
                    List <Object> item = iterator.next();
                    Student student = new Student();
                    //学生姓名
                    String name = item.get(0).toString();

                    //学生邮箱
                    String email = item.get(1).toString();

                    //毕业年份
                    String grate = item.get(2).toString();
                    Integer year = Integer.valueOf(grate.substring(0,grate.indexOf(".0")-2));

                    //学校
                    String school = item.get(3).toString();

                    //图论班级
                    String tlClass = item.get(4).toString();
                    student.setName(name);
                    student.setEmail(email);
                    student.setGraduate_time(year.toString());
                    student.setSchool(school);
                    student.setClass_name(tlClass);

                    students.add(student);
                }

                //将解析出的学生信息插入到数据库
                studentMapper.batchInsert(students);
            }

        } catch (Exception e) {

            e.printStackTrace();
            return "fail";
        }

        return "success";
    }
}